package br.com.musclebook.service;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.com.musclebook.entity.User;

class UserDAO extends BaseDAO {

    public User find(Long id) {
	EntityManager em = this.getEm();

	Query query = em.createNamedQuery("User.findById", User.class);
	query.setParameter("id", id);

	User user = (User) query.getSingleResult();

	return user;
    }

    public User insert(User user) {
	EntityManager em = this.getEm();
	em.persist(user);
	return user;
    }

    public void update(User user) {
	EntityManager em = this.getEm();
	em.merge(user);
    }

    public User authenticate(String username, String password) {
	EntityManager em = this.getEm();

	Query query = em.createNamedQuery("User.authenticate", User.class);
	query.setParameter("username", username);
	query.setParameter("password", password);
	try {
	    User user = (User) query.getSingleResult();
	    return user;
	} catch (NoResultException e) {
	    // TODO: handle exception
	}

	return null;
    }

}
